package com.example.easyexceldemo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.example.easyexceldemo.excelModel.DemoData;
import com.example.easyexceldemo.vo.DemoDataVO;
import com.example.easyexceldemo.vo.ParamVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author wangbao
 * @date 2021/7/19 17:33
 */
@RestController
@RequestMapping("/excel")
public class EasyExcelController {


    public static List<DemoDataVO> demoData = new LinkedList<>();

    static {
        for (int i = 0; i < 100; i++) {
            DemoDataVO demoData1 = new DemoDataVO();
            demoData1.setString("测试");
            demoData1.setData(new Date());
            demoData1.setIntNum(new Integer(1));
            demoData1.setDoubleNum(new Double(12.12));
            demoData.add(demoData1);
        }
    }

    @RequestMapping("/export")
    public void download(@RequestBody ParamVO paramVO, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String param1 = paramVO.getParam1();
        System.out.println(param1);
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try {
            // 测试失败响应json
           // double a = 1 / 0;
            EasyExcel.write(response.getOutputStream(), DemoData.class).sheet("模板").doWrite(demoData);
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}
